package com.example.schoolexam2.intercepter;


import com.example.schoolexam2.utils.JwtUtils;
import com.example.schoolexam2.vo.JsonData;
import com.google.gson.Gson;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class LoginIntercepter implements HandlerInterceptor {

    @Value("${interceptors.auth-ignore-uris}")
    private String authIgnoreUris;
    Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("进入拦截器了");
        String uri = request.getRequestURI();
        logger.info("拦截路径是{}",uri);
        System.out.println(uri);
        System.out.println("无需拦截的接口路径：" + authIgnoreUris);
        String[] authIgnoreUriArr = authIgnoreUris.split(",");
        for (String s : authIgnoreUriArr) {
            if (s.equals(uri)){
                return true;
            }
        }
        String token=request.getHeader("Access-Token");
        if (token ==null){
            token=request.getParameter("token");
        }
        if (token!=null){
            //请求是携带参数的，获取参数
            Claims claims = JwtUtils.checkToken(token);
            if (claims == null){
                sendJsonMessage(response, JsonData.buildError("token无效，请重新登录"));
                return false;
            }
            // 用户的的主键id
            String id = (String) claims.get("id");
            // 用户名
            String username = (String) claims.get("name");
            //用户的角色id
//            String role =(String) claims.get("role");
            // 把这两个参数放到请求中，从而可以在controller中获取到，不需要在controller中在用Jwt解密了,request.getAttribute("属性名")即可获取
            request.setAttribute("id", id);
            request.setAttribute("name", username);
//            request.setAttribute("role",role);
            return true;
        }
        return false;
    }
    public static void sendJsonMessage(HttpServletResponse response, Object obj) throws Exception {
        Gson g = new Gson();
        response.setContentType("application/json; charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.print(g.toJson(obj));
        writer.close();
        response.flushBuffer();
    }
}
